package com.zb.influx;

import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class InfluxReposityory {

    @Autowired
    private InfluxDB influxDB;

    @Value("${spring.influx.db}")
    private String dbName;

    /**
     * 通用的查询方法
     *
     * @param ql
     * @param clazz
     * @return
     * @param <T>
     */
    public <T>List<T> query(String ql,Class<T> clazz){
        QueryResult queryResult = influxDB.query(new Query(ql, dbName));
        influxDB.close();
        InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
        return resultMapper.toPOJO(queryResult,clazz);
    }

    /**
     * 通用的添加方法
     *
     * @param param
     */
    public void add(Object param) {
        Point.Builder builder = Point.measurementByPOJO(param.getClass());
        Point point = builder.addFieldsFromPOJO(param)
                .time(LocalDateTime.now().plusHours(8).toInstant(ZoneOffset.of("+8")).toEpochMilli(), TimeUnit.MILLISECONDS).build();
        influxDB.setDatabase(dbName);
        influxDB.write(point);
        influxDB.close();
    }


}
